<template>
  <div class="file-upload">
    <!-- 文件上传按钮 -->
    <div class="upload-btn" @click="triggerFileInput">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
        <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" />
      </svg>
      <span>文件</span>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input
      ref="fileInput"
      type="file"
      multiple
      :accept="acceptTypes"
      @change="handleFileSelect"
      style="display: none"
    />

    <!-- 上传进度显示 -->
    <div v-if="uploading" class="upload-progress">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
      </div>
      <span class="progress-text">{{ uploadProgress }}%</span>
    </div>

    <!-- 文件预览 -->
    <div v-if="selectedFiles.length > 0" class="file-preview">
      <div v-for="(file, index) in selectedFiles" :key="index" class="file-item">
        <div class="file-info">
          <span class="file-name">{{ file.name }}</span>
          <span class="file-size">{{ formatFileSize(file.size) }}</span>
        </div>
        <button @click="removeFile(index)" class="remove-btn">×</button>
      </div>
      <div class="preview-actions">
        <button @click="uploadFiles" :disabled="uploading" class="upload-btn-action">
          {{ uploading ? '上传中...' : '发送文件' }}
        </button>
        <button @click="clearFiles" :disabled="uploading" class="cancel-btn">取消</button>
      </div>
    </div>
  </div>
</template>

<script>
import http from '../utils/http'

export default {
  name: 'FileUpload',
  props: {
    acceptTypes: {
      type: String,
      default: 'image/*,video/*,audio/*,.pdf,.doc,.docx,.txt'
    },
    maxSize: {
      type: Number,
      default: 50 * 1024 * 1024 // 50MB
    },
    maxFiles: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      selectedFiles: [],
      uploading: false,
      uploadProgress: 0
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click()
    },

    handleFileSelect(event) {
      const files = Array.from(event.target.files)
      
      // 验证文件数量
      if (files.length > this.maxFiles) {
        alert(`最多只能选择 ${this.maxFiles} 个文件`)
        return
      }

      // 验证文件大小
      const oversizedFiles = files.filter(file => file.size > this.maxSize)
      if (oversizedFiles.length > 0) {
        alert(`文件大小不能超过 ${this.formatFileSize(this.maxSize)}`)
        return
      }

      this.selectedFiles = files
      event.target.value = '' // 清空input值，允许重复选择同一文件
    },

    removeFile(index) {
      this.selectedFiles.splice(index, 1)
    },

    clearFiles() {
      this.selectedFiles = []
      this.uploadProgress = 0
    },

    async uploadFiles() {
      if (this.selectedFiles.length === 0) return

      this.uploading = true
      this.uploadProgress = 0

      try {
        const formData = new FormData()
        
        if (this.selectedFiles.length === 1) {
          // 单文件上传
          formData.append('file', this.selectedFiles[0])
          
          const response = await http.post('/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: (progressEvent) => {
              this.uploadProgress = Math.round(
                (progressEvent.loaded * 100) / progressEvent.total
              )
            }
          })

          if (response.data.success) {
            this.$emit('file-uploaded', response.data.file)
          }
        } else {
          // 多文件上传
          this.selectedFiles.forEach(file => {
            formData.append('files', file)
          })

          const response = await http.post('/upload/multiple', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            onUploadProgress: (progressEvent) => {
              this.uploadProgress = Math.round(
                (progressEvent.loaded * 100) / progressEvent.total
              )
            }
          })

          if (response.data.success) {
            this.$emit('files-uploaded', response.data.files)
          }
        }

        // 上传成功后清空选择
        this.clearFiles()
        
      } catch (error) {
        console.error('文件上传失败:', error)
        alert('文件上传失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.uploading = false
      }
    },

    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
  }
}
</script>

<style scoped>
.file-upload {
  position: relative;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  background: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.upload-btn:hover {
  background: #e0e0e0;
}

.upload-progress {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-bar {
  flex: 1;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #07c160;
  transition: width 0.3s;
}

.progress-text {
  font-size: 12px;
  color: #666;
}

.file-preview {
  margin-top: 8px;
  padding: 8px;
  background: #f9f9f9;
  border-radius: 4px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px 0;
  border-bottom: 1px solid #eee;
}

.file-item:last-child {
  border-bottom: none;
}

.file-info {
  flex: 1;
}

.file-name {
  display: block;
  font-size: 14px;
  color: #333;
}

.file-size {
  font-size: 12px;
  color: #666;
}

.remove-btn {
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  font-size: 18px;
  padding: 0 4px;
}

.remove-btn:hover {
  color: #f56c6c;
}

.preview-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.upload-btn-action {
  padding: 6px 12px;
  background: #07c160;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.upload-btn-action:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.cancel-btn {
  padding: 6px 12px;
  background: #f0f0f0;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}
</style>
